package com.chat.provider.rpc;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.base64.Base64Decoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;

/**
 * @Auther created by haoteng on 2019/08/16
 */
//@Component
public class NettyService {

    public static Semaphore semaphore = new Semaphore(1);

    final static Logger logger = LoggerFactory.getLogger(NettyService.class);

    public void initNettyServer(Integer port) {
        start(port);
    }

    private void start(Integer port) {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        EventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        EventLoopGroup workLoopGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossLoopGroup, workLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .option(ChannelOption.SO_BACKLOG, 1024 * 1024)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            // 处理分割符
                            ByteBuf delemiter = Unpooled.buffer().writeBytes("&".getBytes());
                            channel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,
                                    true, true, delemiter));
                            channel.pipeline().addLast(new Base64Decoder());
                            channel.pipeline().addLast(new DemoServerInChannelHandler());
                        }
                    });

            ChannelFuture f = bootstrap.bind(8888).sync();
            semaphore.release();
            System.out.println(Thread.currentThread().getName() + ",服务器开始监听端口，等待客户端连接.........");

            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            bossLoopGroup.shutdownGracefully();
            workLoopGroup.shutdownGracefully();
        }
    }

}
